import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import { Form, Button, Modal, Input } from 'antd';
import moment from 'moment';
import router from 'umi/router';
import { formatMessage } from 'umi-plugin-react/locale';
import SelectForm from '@/components/SelectForm';
import RightDraw from '@/components/RightDraw';
import AdSelect from '@/components/AdSelect';
import AdButton from '@/components/AdButton';
import ManageList from '@/components/ManageList';
import prompt from '@/components/Prompt';
import AntdFormItem from '@/components/AntdFormItem';
import AntdInput from '@/components/AntdInput';
import TableButtons from '@/components/TableButtons';
import StandardTable from '@/components/StandardTable';
import { queryDict, formateDateToMin, formatPrice } from '@/utils/common';
import { supplierColumns } from '@/pages/Common/common';
import AdSearch from '@/components/AdSearch';
import { allDictList } from '@/utils/constans';
import SearchSelect from '@/components/SearchSelect';
import {
  selectBillList,
  saveAllValues,
  renderTableAdSelect,
  renderTableAdSearch,
  codes,
  allDispatchType,
  billStatusList,
  allUrl,
  routeUrl,
  selectBillDetailAndInfo,
} from './utils';
import BillDetail from './BillDetail';
import { tsImportEqualsDeclaration } from '@babel/types';

const { confirm } = Modal;

@ManageList
@connect(({ vehicle, loading, component }) => ({
  billList: vehicle.billList,
  billDetail: vehicle.billDetail,
  formValues: vehicle.formValues,
  dictObject: component.dictObject,
  searchValue: component.searchValue,
  loading: loading.effects[allDispatchType.list],
}))
@Form.create()
export default class BillList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      expandForm: false,
      visible: false,
      detailId: '',
      recordStatus: '',
      selectedRows: [],
      company: [],
    };
    this.className = 'bill-table';
  }

  componentWillMount() {
    // 查询字典项
    const allDict = [allDictList.currencyType, allDictList.payCompany, allDictList.billType];
    queryDict({ props: this.props, allDict });
  }

  componentDidMount() {
    selectBillList({ props: this.props });
  }

  /**
   * form 查找条件 重置
   */
  handleFormReset = () => {
    // console.log('this.props', this.props);
    const { form } = this.props;
    const props = { props: this.props };
    form.resetFields();
    this.setState({
      company: [],
    });
    saveAllValues({ payload: { formValues: {} }, ...props });
    selectBillList({ ...props });
  };

  /**
   * form 查找条件 查询
   */
  handleSearch = formValues => {
    if (!formValues) return;
    const { company } = this.state;
    const { mdsCompanyId, ...value } = formValues;

    if (company.length > 0) {
      const mdsCompanyId = company.map(v => {
        return v.customerCode;
      });
      value.mdsCompanyId = mdsCompanyId.join(',');
    }
    saveAllValues({ props: this.props, payload: { formValues: value } });
    selectBillList({ props: this.props, payload: value });
  };

  /**
   * table 表格 分页操作
   */
  handleStandardTableChange = param => {
    const { formValues } = this.props;
    selectBillList({ payload: { ...formValues, ...param }, props: this.props });
  };

  //详情
  showDetail = (e, detailId, recordStatus) => {
    e.stopPropagation();
    this.handleStateChange([{ detailId }, { recordStatus }, { visible: true }]);
  };

  handleStateChange = (options = []) => {
    options.map(item => {
      this.setState(item);
    });
  };

  //新建
  handleAdd = () => {
    router.push(routeUrl.add);
  };

  //编辑
  handleEdit = () => {
    const { detailId } = this.state;
    this.handleStateChange([{ visible: false }]);
    router.push(`${routeUrl.edit}/${detailId}`);
  };

  columns = [
    {
      title: '单据号',
      dataIndex: 'billNo',
      render: (text, record) => (
        <AdButton
          mode="a"
          onClick={e => this.showDetail(e, record.id, record.status)}
          text={text}
          code={codes.showDetail}
        />
      ),
      fixed: this.props.isMobile ? false : true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: text => renderTableAdSelect({ props: this.props, value: text, data: billStatusList }),
      width: 80,
    },
    {
      title: '类型',
      dataIndex: 'type',
      width: 80,
      render: text =>
        renderTableAdSelect({ props: this.props, value: text, key: allDictList.billType }),
    },
    {
      title: 'OA单号',
      dataIndex: 'oaNo',
    },
    {
      title: '所属公司',
      dataIndex: 'mdsCompanyName',
      render: text => <span title={text}>{text}</span>,
      width: 250,
    },
    {
      title: '应付币种',
      dataIndex: 'currencyType',
      render: text =>
        renderTableAdSelect({
          props: this.props,
          value: text,
          key: allDictList.currencyType,
        }),
      width: 100,
    },
    {
      title: '应付金额',
      dataIndex: 'payable',
      width: 100,
      render: text => <span>{formatPrice(text)}</span>,
    },
    {
      title: '实付币种',
      dataIndex: 'realCurrencyType',
      render: text =>
        renderTableAdSelect({
          props: this.props,
          value: text,
          key: allDictList.currencyType,
        }),
      width: 100,
    },
    {
      title: '实付金额',
      dataIndex: 'realPayable',
      width: 100,
      render: text => <span>{formatPrice(text)}</span>,
    },
    {
      title: '付款对象',
      dataIndex: 'relationObj',
      render: text => {
        return <span title={text}>{text}</span>;
      },
      width: 200,
    },

    {
      title: '银行卡',
      dataIndex: 'bankCard',
      render: text => {
        return <span title={text}>{text}</span>;
      },
    },
    {
      title: '支付公司',
      dataIndex: 'payCompany',
      render: text =>
        renderTableAdSelect({
          props: this.props,
          value: text,
          key: allDictList.payCompany,
        }),
      width: 200,
    },
    {
      title: '创建人',
      dataIndex: 'createBy',
      width: 100,
      render: text => (
        <AdSearch
          label="loginName"
          name="sysName"
          value={this.props.searchValue[text]}
          onlyRead={true}
        />
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      render: text => <span>{text ? moment(text).format(formateDateToMin) : ''}</span>,
    },
    {
      title: '提交人',
      dataIndex: 'commitBy',
      width: 100,
      render: text => (
        <AdSearch
          label="loginName"
          name="sysName"
          value={this.props.searchValue[text]}
          onlyRead={true}
        />
      ),
    },
    {
      title: '提交时间',
      dataIndex: 'commitTime',
      render: text => <span>{text ? moment(text).format(formateDateToMin) : ''}</span>,
    },
    {
      title: '更新人',
      dataIndex: 'updateBy',
      width: 100,
      render: text => (
        <AdSearch
          label="loginName"
          name="sysName"
          value={this.props.searchValue[text]}
          onlyRead={true}
        />
      ),
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      render: text => <span>{text ? moment(text).format(formateDateToMin) : ''}</span>,
    },
    // {
    //   title: '事由',
    //   dataIndex: 'reasons',
    //   render: text => <span title={text}>{text}</span>,
    // },
    {
      title: '备注',
      dataIndex: 'remarks',
      render: text => <span title={text}>{text}</span>,
    },
  ];

  removeBill = (flag, type) => {
    const { dispatch, formValues } = this.props;
    const { selectedRows, detailId, visible } = this.state;
    const ids = selectedRows.map(v => {
      return v.id;
    });
    let _ids=flag ? [detailId] : ids
    
    confirm({
      title: `确定要${type === 'recall' ? '撤回' : '删除'}这条数据吗？`,
      content: ' ',
      okText: '确定',
      okType: type === 'recall' ? '' : 'danger',
      cancelText: '取消',
      onOk: () => {
        console.log('type!!!!',type,ids)
        dispatch({
          type: type === 'recall' ? allDispatchType.recallTmsBill : allDispatchType.remove,
          payload: { ids: _ids },
          callback: data => {
            if (!data) return;
            this.setState({ visible: false, selectedRows: [] });
            selectBillList({ props: this.props, payload: formValues });
          },
        });
      },
    });
  };
  // 提交审核
  commitBill = flag => {
    const { dispatch, formValues } = this.props;
    const { selectedRows, detailId } = this.state;
    if (selectedRows.filter(item => item.status !== 'DRAFT').length > 0) {
      prompt({ content: '只有状态是草稿的账单才能提交审核！', type: 'warn' });
      return;
    }
    const ids = selectedRows.map(v => {
      return v.id;
    });
    confirm({
      title: '单据提交后，将不允许再进行修改，确认提交？',
      content: ' ',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        dispatch({
          type: allDispatchType.commit,
          payload: { ids: flag ? [detailId] : ids },
          callback: data => {
            if (!data) return;
            this.setState({
              selectedRows: [],
            });
            if (flag) {
              selectBillDetailAndInfo({
                type: allDispatchType.detail,
                payload: { id: detailId },
                props: this.props,
                callback: data => {
                  if (!data) return;
                  this.setState({
                    recordStatus: data.status,
                  });
                },
              });
            }
            selectBillList({ props: this.props, payload: formValues });
          },
        });
      },
    });
  };
  getValue = (values, type) => {
    this.setState({
      [type]: values,
    });
  };

  print = () => {
    const { billDetail } = this.props;
    const { detailId } = this.state;
    const detail = billDetail[detailId] || {};
    if (detail.oaNo) {
      window.open(`${routeUrl.print}/${detailId}`);
    } else {
      prompt({ content: '正在同步OA系统，请稍候... ', type: 'warn' });
    }
  };

  render() {
    const { billList, loading, form, isMobile, dictObject } = this.props;
    const { expandForm, detailId, visible, recordStatus, selectedRows } = this.state;

    const commonParams = {
      getFieldDecorator: form.getFieldDecorator,
    };
    const firstFormItem = (
      <AntdFormItem label="类型" code="type" {...commonParams}>
        <AdSelect isExist={true} data={dictObject[allDictList.billType]} />
      </AntdFormItem>
    );
    const secondFormItem = (
      <AntdFormItem label="状态" code="status" {...commonParams}>
        <AdSelect isExist={true} data={billStatusList} mode="multiple" />
      </AntdFormItem>
    );
    // secondForm 参数
    const otherFormItem = [
      [
        <AntdFormItem label="所属公司" code="mdsCompanyId" {...commonParams}>
          <SearchSelect
            dataUrl={allUrl.companyList}
            selectedData={this.state.company} // 选中值
            multiple={false} // 是否多选
            showValue="customerName"
            searchName="customerName"
            allowClear={true}
            columns={supplierColumns} // 表格展示列
            onChange={values => this.getValue(values, 'company')} // 获取选中值
            scrollX={400}
            id="bill2-operate-3"
          />
        </AntdFormItem>,
      ],
      [
        <AntdFormItem label="付款对象" code="relationObj" {...commonParams}>
          <Input />
        </AntdFormItem>,
        <AntdFormItem label="账单号" code="billNo" {...commonParams}>
          <Input />
        </AntdFormItem>,
        <AntdFormItem label="OA单号" code="oaNo" {...commonParams}>
          <Input />
        </AntdFormItem>,
      ],
      ['operatorButtons'],
    ];
    const selectFormParams = {
      firstFormItem,
      secondFormItem,
      otherFormItem,
      form,
      className: this.className,
      handleFormReset: this.handleFormReset,
      handleSearch: this.handleSearch,
      toggleForm: expandForm => {
        this.handleStateChange([{ expandForm }]);
      },
      code: codes.select,
    };

    //1-1 可撤回的账单  审核中：AUDITING
    const recallAble = selectedRows.length > 0 && selectedRows.every(v => v.status === 'AUDITING');
    //1-2 可提交审核的账单  草稿：DRAFT
    const commitAble = selectedRows.length > 0 && selectedRows.every(v => v.status === 'DRAFT');
    //1-3 可删除的账单  草稿：'DRAFT', 已退回：'BACK'
    const removeAble =
      selectedRows.length > 0 &&
      selectedRows.every(v => v.status === 'DRAFT' || v.status === 'BACK');

    const tableButtonsParams = {
      handleAdd: this.handleAdd,
      // pagination: billList.pagination,
      // selectedLength: selectedRows.length,
      buttons: (
        <span>
          <AdButton
            disabled={!removeAble}
            onClick={() => this.removeBill(0)}
            text="删除"
            ghost
            type="danger"
            code={codes.remove}
          />
          <AdButton
            style={{ marginLeft: 8 }}
            disabled={!recallAble}
            onClick={() => this.removeBill(0, 'recall')}
            text="撤回"
            // ghost
            // type="danger"
            // code={codes.remove}
          />
          <AdButton
            style={{ marginLeft: 8 }}
            disabled={!commitAble}
            onClick={() => this.commitBill()}
            text="提交审核"
            code={codes.commitBatch}
          />
        </span>
      ),
      code: codes.add,
    };

    // 详情 参数
    const _status = recordStatus == 'DRAFT' || recordStatus == 'BACK';
    const rightDrawParams = {
      isMobile,
      visible,
      title: '账单详情',
      code: codes.showDetail,
      closeDetail: this.handleStateChange.bind(this, [{ visible: false }]),
      buttons: (
        <>
          <AdButton
            onClick={() => this.removeBill(1)}
            disabled={!_status}
            text="删除"
            type="danger"
            ghost
            code={codes.remove}
          />

          <Button.Group style={{ marginLeft: 8 }}>
            <AdButton
              onClick={() => this.commitBill(1)}
              disabled={!_status}
              text="提交"
              code={codes.commitBatch}
            />
            <AdButton
              onClick={() => this.print()}
              text="打印预览"
              disabled={recordStatus === 'DRAFT'}
            />
            <AdButton
              type="primary"
              onClick={this.handleEdit}
              disabled={!_status}
              text="编辑"
              code={codes.edit}
            />
          </Button.Group>
        </>
      ),
    };

    return (
      <Fragment>
        <SelectForm {...selectFormParams} />
        <TableButtons {...tableButtonsParams} />
        <StandardTable
          loading={loading}
          data={billList}
          selectedRows={selectedRows}
          onSelectRow={selectedRows => {
            this.handleStateChange([{ selectedRows }]);
          }}
          columns={this.columns}
          onPaginationChange={this.handleStandardTableChange}
          expandForm={expandForm}
          className={this.className}
          code={codes.page}
          //   disabledSelectedRows={{ code: ['status'], value: ['DRAFT', 'BACK'] }}
          //   getCheckboxProps={record => {
          //     const status = record.status;
          //     const checked = status === 'DRAFT' || status === 'BACK';
          //     return !checked;
          //   }}
        />
        <RightDraw {...rightDrawParams}>
          <BillDetail detailId={detailId} />
        </RightDraw>
      </Fragment>
    );
  }
}
